package com.share.dubbo.es.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Configuration
public class EsConfig {

    /*client模式*/
    @Value("${es.client.cluster.name}")
    private String clusterName;

    @Value("${es.client.cluster.nodes}")
    private String clusterNodes;

    /*rest模式*/
    @Value("${es.rest.schema:http}")
    private String schema;

    @Value("${es.rest.url}")
    private String url;

    @Value("${es.rest.timeout:5000}")
    private Integer timeout;

    /**
     * 6.8版本前常被使用,后面高版本不推荐使用,连接池不稳定,心跳也有问题
     * @return
     */
    @Bean
    public TransportClient getObject() throws Exception {
        Settings settings = Settings.builder().put("cluster.name", clusterName).build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        for (String clusterNode : clusterNodes.split(",")) {
            String[] split = clusterNode.split(":");
            client.addTransportAddress(new TransportAddress(InetAddress.getByName(split[0]), Integer.parseInt(split[1])));
        }
        log.info("es的client模式初始化完毕!!!");
        return client;
    }

    /**
     * 高版本---官方推荐使用(7.0)
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        String hosts[] = this.url.split(",");
        if (hosts == null) {
            log.error("es的rest模式初始化失败!");
        }
        List<HttpHost> hostList = new LinkedList<>();
        for (String clusterNode : hosts) {
            String[] hostPort = clusterNode.split(":");
            hostList.add(new HttpHost(hostPort[0], Integer.parseInt(hostPort[1])));
        }
        RestClientBuilder builder = RestClient.builder((HttpHost[]) hostList.toArray(new HttpHost[hosts.length]));
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            return requestConfigBuilder.setSocketTimeout(this.timeout); // 设置超时
        });
        log.info("es的rest-high模式初始化完毕!!!");
        return new RestHighLevelClient(builder);
    }


    /**
     * 低版本的RestClient非常不好用,啥都不支持，因此现在都使用高版本的RestHighLevelClient
     * HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);
     * Response response = restClient.performRequest("GET", "/some_important_index/_search",params, entity);"
     */
    @Bean
    public RestClient restClient(@Autowired RestClientBuilder restClientBuilder) {
        RestClient restClient = restClientBuilder.build();
        log.info("es的rest-low模式初始化完毕!!!");
        return restClient;
    }

    @Bean
    public RestClientBuilder restClientBuilder() {
        String hosts[] = this.url.split(",");
        if (hosts == null) {
            log.error("es的rest模式初始化失败!");
        }
        List<HttpHost> hostList = new LinkedList<>();
        for (String clusterNode : hosts) {
            String[] hostPort = clusterNode.split(":");
            hostList.add(new HttpHost(hostPort[0], Integer.parseInt(hostPort[1])));
        }
        RestClientBuilder builder = RestClient.builder((HttpHost[]) hostList.toArray(new HttpHost[hosts.length]));
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            return requestConfigBuilder.setSocketTimeout(this.timeout); // 设置超时
        });
        return builder;
    }
}